package com.ruoyi.stock2.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OtherUtils {
    private static final Logger log = LoggerFactory.getLogger(OtherUtils.class);
    public static String getLocalDateStr(Date date, String formatter) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter);
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);
        String dateStr = dateTimeFormatter.format(localDateTime);

        return dateStr;
    }
    /**
     * 执行命令
     *
     * @param cmd
     * @throws IOException
     */
    public static List<String> exec(String cmd) throws IOException, InterruptedException {
        long startTime = System.currentTimeMillis();

        Process process = Runtime.getRuntime().exec(cmd);
        List<String> list = printMessage(process.getInputStream());
        if (process.waitFor() == 0) {
            log.warn("命令执行成功(总耗时:" + (System.currentTimeMillis() - startTime) / 1000 + "秒)");
        } else {
            log.warn("命令执行成功失败");
        }
        return list;
    }

    /**
     * 读取流到控制台(防止死锁)
     *
     * @param input
     */
    private static List<String> printMessage(final InputStream input) {
        List<String> list = new ArrayList(100);

        Reader reader = new InputStreamReader(input, Charset.forName("GBK"));
        BufferedReader bf = new BufferedReader(reader);
        String line = null;
        try {

            while ((line = bf.readLine()) != null) {

                list.add(line);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
        return list;
    }

}
